package com.bolt.report.engine.query;

import com.bolt.common.utils.SpringContextUtil;
import com.bolt.convention.exception.ServiceException;
import com.bolt.report.definition.DataSetDefinition;
import com.bolt.report.engine.BRDataSource;
import com.bolt.report.engine.CollectionDataSource;
import com.bolt.report.engine.DataProvider;

import java.util.List;
import java.util.Map;

public class SpringBeanQueryExecute implements QueryExecute {

    private DataSetDefinition dataSetDefinition;

    private Map<String, Object> parameters;

    public SpringBeanQueryExecute(DataSetDefinition dataSetDefinition, Map<String, Object> parameters) {
        this.dataSetDefinition = dataSetDefinition;
        this.parameters = parameters;
    }

    @Override
    public BRDataSource createBRDataSource() {
        try {
            if (SpringContextUtil.containsBean(dataSetDefinition.getSpringKey())) {
                DataProvider dataProvider = (DataProvider) SpringContextUtil.getBean(dataSetDefinition.getSpringKey());
                List data = dataProvider.loadData(parameters);
                return new CollectionDataSource(data);
            } else {
                throw new ServiceException("The supplied spring DataProvider is null");
            }
        } catch (Exception ex) {
            throw new ServiceException(ex);
        }

    }


    @Override
    public List<?> queryData() {
        return ((CollectionDataSource) createBRDataSource()).getData();
    }
}